<%@page import="java.security.Principal"%>
<%@ page import="org.apache.log4j.Logger" %>
<%@ page import="it.trekker.prefetch.IExcursionDAOWithPrefetch" %>
<%@ page import="it.trekker.upload.json.IFileLoaderFactory" %>
<%@ page import="it.elbuild.jcoord.LatLng" %>
<%@ page import="it.elbuild.jcoord.resolver.GeoCodeResolver" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="it.trekker.dao.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="it.trekker.upload.*" %>
 
<%!
String printExcursionTableRow(Excursion excursion) {
	
	if(excursion == null)
		return "";
	
	SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss");
	StringBuffer html = new StringBuffer();
	
	html
		.append("<tr>")
		.append("<td>")
		.append("<a href='excursion_details.jsp?id=" + excursion.getId() + "'>")
			.append(excursion.getId())
		.append("</a>")
		.append("</td>")
		.append("<td>")
		.append(excursion.getName())
		.append("</td>")
		.append("<td>")
		.append(df.format(excursion.getDate()))
		.append("</td>")
		.append("<td>")
		.append(excursion.getUser().getUsername())
		.append("</td>")
		.append("</tr>");
	
	return html.toString(); 
}

String printExcursionTableRows(List<Excursion> excursions) {
	if(excursions == null)
		return "";
	
	StringBuffer html = new StringBuffer();
	
	for(Excursion excursion : excursions) {
		html.append(printExcursionTableRow(excursion));
	}	
	
	return html.toString(); 
}
%>

<%
Logger logger = Logger.getLogger("it.trekker.search.jsp");

DAOFactory daoFactory = DAOFactory.getDAOFactory(application.getInitParameter("dao"));
IExcursionDAOWithPrefetch excursionDAO = daoFactory.getExcursionDAOWithPrefetch();
IUserDAO userDAO = daoFactory.getUserDAO();

// Configure ExcursionDAOWithPrefetch
//double searchingRadius = Integer.parseInt(application.getInitParameter("searching_radius"));
//excursionDAO.setSearchingRadius(searchingRadius);
//boolean cacheEnabled = Boolean.parseBoolean(application.getInitParameter("cache_enabled"));
excursionDAO.setCacheEnabled(false);

List<Excursion> excursionList = new ArrayList<Excursion>();
String searchType = request.getParameter("searchType");

if(searchType != null && searchType.equals("address")) {
	String city = request.getParameter("city");
	String province = request.getParameter("province");
	String address = request.getParameter("address");
	
	if(
			(city == null || city.isEmpty()) && 
			(province == null || province.isEmpty()) && 
			(address == null || address.isEmpty())
	) {
		excursionList = excursionDAO.findAllExcursions();
	}
	else {
		
		LatLng coord = GeoCodeResolver.findExactCoordForAddress(city, province, address);
		
		GPSCoordinate gpsCoord = new GPSCoordinate();
		gpsCoord.setLatitude(coord.getLat().doubleValue());
		gpsCoord.setLongitude(coord.getLng().doubleValue());
		
		excursionList = excursionDAO.findCloseExcursions(gpsCoord);
	}
}
else if(searchType != null && searchType.equals("username")) {
	String username = request.getParameter("username");
	
	if(username != null && !username.isEmpty()) {
		User user = userDAO.findUserByName(username);
		
		if(user != null) {
			excursionList = excursionDAO.findExcursionsByUser(user);
		}
	}
}
else {
	Principal principal = request.getUserPrincipal();
	String principalName;
	if(principal != null)
		principalName = request.getUserPrincipal().getName();
	else
		principalName = "";
	
	if(principalName != null && !principalName.isEmpty()) {
		User user = userDAO.findUserByName(principalName);
		
		if(user != null) {
			excursionList = excursionDAO.findExcursionsByUser(user);
		}
	}
}
%>

<html>

	<head>
		<title>Trekker</title>
	
		<meta http-equiv="Pragma" content="no-cache"/>
		<meta http-equiv="Expires" content="Mon, 01 Jan 1996 23:59:59 GMT"/>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<meta name="Author" content="you">

		<link rel="StyleSheet" href="styles/default.css" type="text/css" media="all" />
		
		<script type="text/javascript">
			function clearForm(oForm) {
				var elements = oForm.elements;
					oForm.reset();
	
					for (i = 0; i < elements.length; i++) {
						field_type = elements[i].type.toLowerCase();
	
						switch (field_type) {
							case "text":
							case "password":
							case "textarea":
							/* case "hidden": */
								elements[i].value = "";
								break;
	
							case "radio":
							case "checkbox":
								if (elements[i].checked) {
									elements[i].checked = false;
								}
								break;
		
							case "select-one":
							case "select-multi":
								elements[i].selectedIndex = -1;
								break;
		
							default:
								break;
						}
					}
				}
			</script>
	</head>
	
	<body>
		<div id="menu_link">
			<a href="index.jsp">Back to home</a><br />
		</div>
		
		<div id="address_request">
			<h1>Search excursions</h1>
			<form method='POST'>
				<input type="hidden" name="searchType" value="address" />
				<div class="block">
					<label>Address:</label>
					<div class="input"><input name="address" type="textbox" value="Piazza Roma"></div>
				</div>
				<div class="block">
					<label>City:</label>
					<div class="input"><input name="city" type="textbox" value="Marmirolo"></div>
				</div>
				<div class="block">
					<label>Province:</label>
					<div class="input"><input name="province" type="textbox" value="Mantova"></div>
				</div>
				<div class="block">
					<div class="address_button"><input id="submit" type="submit" value="Search close excursions"></div>
					<div class="address_button"><input id="clear_form" type="button" value="Clear" onclick="clearForm(this.form)"></div>
				</div>
			</form>
			
			<form method='POST'>
				<input type="hidden" name="searchType" value="username" />
				<div class="block">
					<label>Username:</label>
					<div class="input"><input name="username" type="textbox" value=""></div>
				</div>
				<div class="block">
					<div class="address_button"><input id="submit" type="submit" value="Search excursions"></div>
					<div class="address_button"><input id="clear_form" type="button" value="Clear" onclick="clearForm(this.form)"></div>
				</div>
			</form>
		</div>
		
		<h1>Excursions</h1>
		
		<div>
			<table class="excursions">
				<thead>
					<tr>
						<th>Id</th>
						<th>Name</th>
						<th>Date</th>
						<th>User</th>
					</tr>
				</thead>
				<%=	printExcursionTableRows(excursionList) %> 
			</table>
		</div>
	</body>

</html>
